<template>
  <div class="container">
    <div class="header">
      <h1>商品管理</h1>
      <div class="actions">
        <el-button type="primary" @click="addProduct">添加商品</el-button>
      </div>
    </div>
    
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option :value="1" label="上架" />
            <el-option :value="0" label="下架" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <el-table :data="productList" style="width: 100%" v-loading="loading">
        <el-table-column type="index" prop="id" label="ID" width="80" />
        <el-table-column label="商品图片" width="120">
          <template #default="scope">
            <div class="image-preview">
              <img 
                style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;" 
                :src="scope.row.imageUrl || 'https://placeholder.pics/svg/100x100'" 
              />
              <div class="image-actions">
                <el-button 
                  type="primary" 
                  size="small"
                  circle
                  @click="previewImage(scope.row.imageUrl)"
                  :disabled="!scope.row.imageUrl">
                  <el-icon><ZoomIn /></el-icon>
                </el-button>
                <el-button 
                  v-if="scope.row.id" 
                  type="primary" 
                  size="small"
                  circle
                  @click="showImageUploadDialog(scope.row)"
                  :disabled="scope.row.status === 0">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="description" label="商品描述" show-overflow-tooltip />
        <el-table-column prop="points" label="所需积分" />
        <el-table-column prop="stock" label="库存" />
        <el-table-column label="创建时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button size="small" @click="editProduct(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(scope.row)">
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button size="small" type="danger" @click="confirmDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 图片上传对话框 -->
    <el-dialog title="上传商品图片" v-model="imageDialogVisible" width="400px">
      <div class="upload-container">
        <el-upload
          class="image-uploader"
          action="#"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleImageChange"
          accept="image/jpeg,image/png,image/gif"
        >
          <el-image 
            v-if="imagePreview" 
            :src="imagePreview" 
            class="uploaded-image"
            fit="cover" />
          <el-icon v-else class="image-uploader-icon"><plus /></el-icon>
        </el-upload>
        <div class="upload-tip">请上传商品图片，建议尺寸 800x800 像素</div>
        <div v-if="imagePreview" class="preview-actions">
          <el-button type="primary" @click="previewImage(imagePreview)">
            <el-icon><ZoomIn /></el-icon> 预览大图
          </el-button>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="imageDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadProductImage" :loading="uploading" :disabled="!imageFile">上传</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="800px" append-to-body center>
      <div class="image-preview-dialog">
        <el-image
          style="width: 100%;"
          :src="previewImageUrl"
          fit="contain"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ZoomIn, Edit } from '@element-plus/icons-vue'
import { pageProducts, deleteProduct, putOnSale, putOffSale, updateProductStatus, updateProduct } from '@/api/product'
import { uploadFile } from '@/api/upload'

const router = useRouter()
const loading = ref(false)
const productList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const searchForm = reactive({
  name: '',
  status: ''
})

// 图片上传相关
const imageDialogVisible = ref(false)
const imageFile = ref(null)
const imagePreview = ref('')
const currentProduct = ref(null)
const uploading = ref(false)
const previewVisible = ref(false)
const previewImageUrl = ref('')

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-';
  const date = new Date(dateTimeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 添加商品
const addProduct = () => {
  router.push('/product/add')
}

// 编辑商品
const editProduct = (row) => {
  router.push(`/product/edit/${row.id}`)
}

// 确认删除
const confirmDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除商品"${row.name}"吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    handleDelete(row.id)
  }).catch(() => {})
}

// 切换商品状态
const toggleStatus = (row) => {
  const action = row.status === 1 ? '下架' : '上架'
  
  ElMessageBox.confirm(
    `确定要${action}商品"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    handleToggleStatus(row)
  }).catch(() => {})
}

// 处理切换状态
const handleToggleStatus = async (row) => {
  try {
    loading.value = true
    if (row.status === 1) {
      // 当前是上架状态，执行下架
      await putOffSale(row.id)
    } else {
      // 当前是下架状态，执行上架
      await putOnSale(row.id)
    }
    
    // 也可以使用统一的接口
    // await updateProductStatus(row.id, row.status === 1 ? 0 : 1)
    
    ElMessage.success(`商品${row.status === 1 ? '下架' : '上架'}成功`)
    fetchData() // 重新加载数据
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 删除商品
const handleDelete = async (id) => {
  try {
    loading.value = true
    await deleteProduct(id)
    ElMessage.success('删除成功')
    fetchData() // 重新加载数据
  } catch (error) {
    console.error('删除失败', error)
    ElMessage.error('删除失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 查询数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.name || undefined,
      status: searchForm.status !== '' ? searchForm.status : undefined
    }
    
    const res = await pageProducts(params)
    if (res && res.code === 200 && res.data) {
      productList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      throw new Error(res.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取商品数据失败', error)
    ElMessage.error('获取商品数据失败：' + (error.message || '未知错误'))
    productList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.status = ''
  currentPage.value = 1
  fetchData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 显示图片上传对话框
const showImageUploadDialog = (product) => {
  currentProduct.value = product
  imagePreview.value = product.imageUrl || ''
  imageFile.value = null
  imageDialogVisible.value = true
}

// 处理图片选择
const handleImageChange = (file) => {
  imageFile.value = file.raw
  // 本地预览
  const reader = new FileReader()
  reader.onload = (e) => {
    imagePreview.value = e.target.result
  }
  reader.readAsDataURL(imageFile.value)
}

// 上传商品图片
const uploadProductImage = async () => {
  if (!imageFile.value || !currentProduct.value) {
    ElMessage.warning('请先选择图片')
    return
  }

  try {
    uploading.value = true
    const res = await uploadFile(imageFile.value, 'product')
    
    if (res && res.code === 200) {
      // 更新商品信息
      const updateData = {
        id: currentProduct.value.id,
        imageUrl: `http://localhost:8080/api`+res.message // 后端返回的图片URL路径
      }
      
      await updateProduct(updateData)
      ElMessage.success('商品图片上传成功')
      imageDialogVisible.value = false
      
      // 重新加载数据以显示最新图片
      fetchData()
    } else {
      throw new Error(res.message || '上传失败')
    }
  } catch (error) {
    console.error('上传商品图片失败', error)
    ElMessage.error('上传商品图片失败：' + (error.message || '未知错误'))
  } finally {
    uploading.value = false
  }
}

// 预览图片
const previewImage = (url) => {
  if (!url) return
  previewImageUrl.value = url
  previewVisible.value = true
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .image-preview {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 5px;
    
    .image-actions {
      display: flex;
      gap: 5px;
    }
  }
  
  .image-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 178px;
    height: 178px;
    margin: 0 auto 10px;
    
    &:hover {
      border-color: var(--el-color-primary);
    }
    
    .image-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .uploaded-image {
      width: 178px;
      height: 178px;
      display: block;
      object-fit: cover;
    }
  }
  
  .upload-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .preview-actions {
      margin-top: 10px;
    }
  }
  
  .image-preview-dialog {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
  }
}
</style> 